package com.devframe.srtp.server.file;

import java.io.File;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.devframe.srtp.Account;
import com.devframe.srtp.SRTPResult;
import com.devframe.srtp.server.parse.SRTPParam;
import com.devframe.srtp.util.common.SRTPThumbUtil;
import com.devframe.srtp.util.enumobj.EnumSRTPAction;

/**
 * 
 * @author 詹保山
 * 替换原有文件
 */
public class SRTPReplaceFileHandler {
	private static final Log log=LogFactory.getLog(SRTPReplaceFileHandler.class);
	private Account account;
	public SRTPReplaceFileHandler(Account account){
		this.account=account;
	}
	
	public SRTPResult process(SRTPParam reqParams){
		SRTPResult result=new SRTPResult();
		result.setCode(false);
		result.setAction(EnumSRTPAction.REPLACE_FILE.getValue());
		
		if(StringUtils.isNotBlank(reqParams.getFilePath()) && reqParams.getFileUpload()!=null){
			String realPath=this.account.getRootPath()+reqParams.getFilePath();
			if(log.isDebugEnabled()){
				log.debug("进行替换文件："+realPath);
			}
			File oldFile=new File(realPath);
			if(oldFile.exists() && oldFile.isFile()){
				oldFile.delete();
			}else{
				result.setMsg("替换的文件不存在");
				return result;
			}
			//判断是是否有缩略图
			String thumbFilePath=SRTPThumbUtil.getThumbImagePath(realPath);
			File thumbFile=new File(thumbFilePath);
			
			boolean thumbBool=false;
			if(thumbFile.exists() && thumbFile.isFile()){
				thumbFile.delete();
				thumbBool=true;
			}
			try {
				 boolean bool=reqParams.getFileUpload().renameTo(oldFile);
				 result.setCode(bool);
				 result.setMsg("文件替换上传成功");
				 result.setFilePath(reqParams.getFilePath());
				 if(bool && thumbBool){
					if(log.isDebugEnabled()){
							log.debug("生成缩略图");
					}
					 //处理缩略图
					SRTPThumbUtil.createThumbImage(oldFile,thumbFile,this.account.getThumbWidth(),this.account.getThumbHeight());
				 }
			} catch (Exception e) {
				e.printStackTrace();
				result.setCode(false);
				result.setMsg("文件替换报错"+e+",acount:"+account);
				log.error("文件替换报错"+e+",acount:"+account);
			}
		}
		return result;
	}
	
	
}
